package com.rescue.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rescue.context.BaseContext;
import com.rescue.forum.dto.MsgPageQueryDTO;
import com.rescue.forum.dto.SendMessageDTO;
import com.rescue.forum.entity.UserMessage;
import com.rescue.forum.vo.MessageCountVO;
import com.rescue.mapper.UserInfoMapper;
import com.rescue.mapper.UserMessageMapper;
import com.rescue.result.PageResult;
import com.rescue.service.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserMessageServiceImpl implements UserMessageService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;

    public void sendMessage(SendMessageDTO sendMessageDTO) {
        Integer SendUserId = BaseContext.getCurrentId();
        UserMessage userMessage = UserMessage.builder().messageType(UserMessage.TYPE_SYS_MESSAGE)
                .sendUserId(SendUserId)
                .receivedUserId(sendMessageDTO.getUserId())
                .sendNickName(userInfoMapper.getByUserId(SendUserId).getNickName())
                .messageContent(sendMessageDTO.getMessage())
                .createTime(LocalDateTime.now())
                .build();
        userMessageMapper.save(userMessage);
    }

    @Override
    public MessageCountVO getMessageCount() {
        return MessageCountVO.builder()
                .sys(userMessageMapper.getCountByType(UserMessage.TYPE_SYS_MESSAGE,BaseContext.getCurrentId()))
                .reply(userMessageMapper.getCountByType(UserMessage.TYPE_COMMENT_MESSAGE,BaseContext.getCurrentId()))
                .likePost(userMessageMapper.getCountByType(UserMessage.TYPE_ARTICLE_LIKE,BaseContext.getCurrentId()))
                .likeComment(userMessageMapper.getCountByType(UserMessage.TYPE_COMMENT_LIKE,BaseContext.getCurrentId()))
                .attachmentDownload(userMessageMapper.getCountByType(UserMessage.TYPE_DOWNLOAD_ATTACHMENTS,BaseContext.getCurrentId()))
                .total(userMessageMapper.getCountByType(null,BaseContext.getCurrentId())).build();
    }

    @Override
    public PageResult page(MsgPageQueryDTO msgPageQueryDTO) {
        PageHelper.startPage(msgPageQueryDTO.getPage(),msgPageQueryDTO.getPageSize());
        Page<UserMessage> page = userMessageMapper.getByTypeAndUserId(msgPageQueryDTO.getMessageType(),BaseContext.getCurrentId());
        return new PageResult(page.getTotal(),page.getResult());
    }
}
